package org.webdb.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.sql.DataSource;

import org.webdb.core.config.DatabaseConfig;
import org.webdb.jdbc.JDBCTableStore.TableKey;

public class JDBCMetaData {

    private static final ArrayList<String> allowedTableTypes = new ArrayList<String>();
    static {
        allowedTableTypes.add("TABLE");
        allowedTableTypes.add("VIEW");
    }
    private String dbmsName;
    private DataSource dataSource;
    private String name;

    private JDBCTableStore tableStore;
    private DatabaseConfig config;

    public JDBCMetaData(String name, DataSource dataSource,
            JDBCTableStore tableStore, DatabaseConfig config)
            throws SQLException {
        this.dataSource = dataSource;
        Connection connection = dataSource.getConnection();
        this.tableStore = tableStore;
        this.name = name;
        this.config = config;
        try {
            DatabaseMetaData jdbcMetaData = connection.getMetaData();
            dbmsName = jdbcMetaData.getDatabaseProductName();
            loadTableNames(jdbcMetaData);
        } finally {
            JDBCUtils.close(connection);
        }
    }

    private JDBCTable defineTable(String schemaName, String tableName)
            throws SQLException {
        Connection connection = dataSource.getConnection();
        try {
            DatabaseMetaData jdbcMetaData = connection.getMetaData();
            DatabaseConfig tableConfig = null;
            try {
                DatabaseConfig tables = config.<DatabaseConfig> getAs("tables");
                tableConfig = tables.<DatabaseConfig> getAs(schemaName + "."
                        + tableName);
            } catch (Exception e) {
            }
            JDBCTable table = new JDBCTable(schemaName, tableName,
                    jdbcMetaData, tableConfig);
            tableStore.store(table);
            return table;
        } finally {
            JDBCUtils.close(connection);
        }
    }

    public String getDBMSName() {
        return dbmsName;
    }

    public String getName() {
        return name;
    }

    public JDBCTable getTable(String schemaName, String tableName) {
        JDBCTable table = tableStore.retrieve(schemaName, tableName);
        if (table != null && table == JDBCTable.NOT_LOADED) {
            try {
                table = defineTable(schemaName, tableName);
            } catch (Exception e) {
                throw new JDBCException(toString() + " Creating JDBCTable "
                        + schemaName + "." + tableName, e);
            }
        }
        return table;
    }

    public boolean hasTable(String clusterName, String documentName) {
        return tableStore.retrieve(clusterName, documentName) != null;
    }

    private List<String> listSchemaNames(DatabaseMetaData jdbcMetaData)
            throws SQLException {
        ResultSet rs = jdbcMetaData.getSchemas();
        try {
            List<String> list = new LinkedList<String>();
            while (rs.next()) {
                list.add(rs.getString(1));
            }
            return list;
        } finally {
            JDBCUtils.close(rs);
        }
    }

    private void loadTableNames(DatabaseMetaData jdbcMetaData)
            throws SQLException {
        List<String> schemaNames = listSchemaNames(jdbcMetaData);
        String[] allowedTableTypesArray = allowedTableTypes
                .toArray(new String[allowedTableTypes.size()]);

        ResultSet rs;
        for (String schema : schemaNames) {
            rs = jdbcMetaData.getTables(null, schema, null,
                    allowedTableTypesArray);
            try {
                while (rs.next())
                    tableStore.store(new TableKey(schema, rs.getString(3)),
                            JDBCTable.NOT_LOADED);
            } finally {
                JDBCUtils.close(rs);
            }
        }
    }
}